$(function() {
    //Declare variable
    var  Username= $( "#txtUsername" ),
           Password= $("#txtPassword"),
           ConfirmPwd=$("#txtConfirmpassword"),
           Email = $("#txtEmail"),
           SsCode= $("#sscode"),
           allFields = $( [] ).add( Username ).add( Password ).add(Email).add(SsCode),
           url="model.php";
           
    
    function checkInputFile( o, n, min ) {
        if (o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Please input " + n + "." );
            return false;
        } else {
            return true;
        }
    }
 
    function updateTips( t ) {
         $(".message").css("display" ,'block');
         $(".message").find("p").html(t); 
        setTimeout(function() {
           $(".message").css("display" ,'none');
        }, 5000 );
    }
    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }
     function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
                min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }
    function checkConfirmPassword(o,c){
        if (o.val() != c.val() ){
            c.addClass( "ui-state-error" );
            updateTips( "Confirm Password ไม่ถูกต้อง " );
            return false;
        } else {
            return true;
        }     
        
    }
    function checkSecurityCode(o){
         if (o.val() != s_code){
          o.addClass( "ui-state-error" );
            updateTips( "Security Code ไม่ถูกต้อง " );
            return false;
        } else {
            return true;
        }     
        
        
    }
    
   $( "#dialog:ui-dialog" ).dialog( "destroy" );
        
          $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 250,
            width: 350,
            modal: true,
            buttons: { 
                "Login": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkInputFile( Username, "username", 1 );
                    bValid = bValid && checkInputFile( Password, "password", 1 );
                    
                    if (bValid){
                        
                         $.ajax({
                            type: 'POST',
                            cache: false,
                            url: url,
                            data: {'m':'login','u':Username.val(),'p':Password.val()},      
                            success: function(data){
                                  var obj=eval('(' + data + ')');
                                   if (obj['msg']==0){
                                       updateTips('Username & Password ไม่ถูกต้อง');
                                  }else{
                                      $( "#dialog-form" ).dialog( "close" );    
                                        window.location="index.php";          
                                    
                                   }             
                              }
                            });
                    }
                },
                "Register":function(){
                    window.location="register.php";                                            
                } 
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });
 
    $(".btnLogin").click(function(){
        $( "#dialog-form" ).dialog( "open" );
    });       
     $("#btnRegister").click(function(){
          var bValid = true;
           // allFields.removeClass( "ui-state-error" );
            bValid = bValid && checkLength( Username, "username", 3, 16 );
            bValid = bValid && checkLength( Password, "password", 5, 16 );
            bValid = bValid && checkRegexp( Username, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
            bValid = bValid && checkRegexp( Email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
            bValid = bValid && checkRegexp( Password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
            bValid = bValid && checkConfirmPassword( Password, ConfirmPwd);
            bValid = bValid && checkSecurityCode($("#sscode"));
            
            if (bValid){
                allFields.removeClass( "ui-state-error" );
                 var dataSet={'m':'add','u':Username.val(),'p':Password.val(),'e':Email.val()};
                 
                $.ajax({
                type: 'POST',
                cache: false,
                url: url,
                data: dataSet,      
                success: function(data){
                   var obj=eval("(" + data + ")");
                    
                     if (obj['msg']=='0'){
                        $(".message").css("display" ,'block');
                        $(".message").find("p").html('Username ซ้ำกับที่มีอยู่ในระบบ');
                        Username.focus();
                    }else{
                        alert('บันทึกข้อมูลเรียบร้อยแล้ว');
                        if (obj['confirm']=='1')
                         window.location="order.php";
                         else
                           window.location="index.php";              
                    }
                }, 
                error:function(jqXHR, textStatus, errorThrown) { 
                    alert(jqXHR+":"+textStatus);
                  }
                });
                 
                
            }
     }); 

});